package com.loop.zerocopy;

import java.io.FileInputStream;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

/**
 * @author zhangxiaolu
 * @since 2023-09-07 22:03
 */
public class IOClient {

    public static void main(String[] args) throws  Exception {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new java.net.InetSocketAddress("127.0.0.1", 7001));
        // 得到一个文件channel
        String fileName = "1.txt";
        FileChannel fileChannel = new FileInputStream(fileName).getChannel();
        // 准备发送
        long startTime = System.currentTimeMillis();

        // 在Linux环境下，一个transferTo方法就可以完成发送
        // 但是在Windows环境下，一次调用transferTo只能发送8M，需要分段发送，所以需要多次调用transferTo方法
        // transferTo 底层使用到了零拷贝
        long transferCount = fileChannel.transferTo(0, fileChannel.size(), socketChannel);
        System.out.println("发送的总的字节数：" + transferCount);
        System.out.println("发送的总的时间：" + (System.currentTimeMillis() - startTime));
        fileChannel.close();
        socketChannel.close();
    }
}
